import 'package:flutter/material.dart';

import 'base_tab_config.dart';

class BaseTabPage extends StatefulWidget {
  /// Tabs
  final List<BaseTabConfig> tabs;

  /// 初始页面
  final int initialIndex;

  /// 滑动类型
  final bool isScrollable;

  /// TabBar背景颜色
  final Color backGroundColor;

  /// Tab的改变事件
  final Function(int index) onTabChanged;

  /// 回调控制器
  final Function(TabController controller) controllerCallback;

  /// 构造函数
  const BaseTabPage(this.tabs, {Key key, this.initialIndex = 0, this.isScrollable = false, this.backGroundColor = Colors.white, this.onTabChanged, this.controllerCallback}) : super(key: key);

  @override
  State<BaseTabPage> createState() => _BaseTabPageState();
}

class _BaseTabPageState extends State<BaseTabPage> with SingleTickerProviderStateMixin {
  TabController _controller;

  @override
  void initState() {
    super.initState();
    this._controller = new TabController(length: widget.tabs.length, initialIndex: widget.initialIndex, vsync: this);
    if (widget.controllerCallback != null) widget.controllerCallback(this._controller);
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Container(child: _buildTabBarWidget(), width: double.infinity, color: widget.backGroundColor, padding: EdgeInsets.zero),
        Expanded(child: TabBarView(controller: this._controller, children: widget.tabs.map((item) => item.child).toList())),
      ],
    );
  }

  Widget _buildTabBarWidget() {
    return TabBar(isScrollable: widget.isScrollable, controller: this._controller, tabs: widget.tabs.map((item) => Text(item.text)).toList(), onTap: _onTabChanged);
  }

  void _onTabChanged(int index) {
    if (widget.onTabChanged != null) widget.onTabChanged(index);
  }

  @override
  void dispose() {
    this._controller.dispose();
    super.dispose();
  }
}
